﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Elentok.Common.Helpers
{
  /// <summary>
  /// String-related helper methods
  /// </summary>
  public static class StringHelper
  {
    /// <summary>
    /// Calculates the edit-distance between the two given strings
    /// </summary>
    /// <param name="string1"></param>
    /// <param name="string2"></param>
    /// <returns></returns>
    public static int CalculateEditDistance(this string string1, string string2)
    {
      int rows = string2.Length + 1;
      int cols = string1.Length + 1;

      int[][] values = new int[rows][];

      for (int row = 0; row < rows; row++)
        values[row] = new int[cols];

      for (int col = 0; col < cols; col++)
        values[0][col] = col;

      for (int row = 0; row < rows; row++)
        values[row][0] = row;

      for (int col = 1; col < cols; col++)
      {
        for (int row = 1; row < rows; row++)
        {
          if (string1[col - 1] == string2[row - 1])
            values[row][col] = values[row - 1][col - 1];
          else
          {
            values[row][col] = Math.Min(Math.Min(
              values[row - 1][col - 1] + 1, // substitute
              values[row][col - 1] + 1),    // insert
              values[row - 1][col] + 1);   // delete
          }
        }
      }

      return values[rows - 1][cols - 1];
    }

  }
}
